import 'package:flutter/material.dart';

class ServiceItem {
  final String id;
  final String name;
  final int port;
  final String ip;
  final IconData icon;
  bool isEnabled;
  final bool isLocal; // 是否为本地扫描的服务
  final bool isRunning; // 本地服务是否正在运行
  final String? tunnelId; // 对应的隧道ID
  final String? customDomain; // 自定义域名
  final String protocol; // 协议类型：http、tcp
  final String? status; // 后端状态：active、inactive

  ServiceItem({
    required this.id,
    required this.name,
    required this.port,
    required this.ip,
    required this.icon,
    this.isEnabled = false,
    this.isLocal = false,
    this.isRunning = false,
    this.tunnelId,
    this.customDomain,
    this.protocol = 'http', // 默认HTTP协议
    this.status,
  });
  
  // 从JSON创建ServiceItem实例
  factory ServiceItem.fromJson(Map<String, dynamic> json) {
    return ServiceItem(
      id: json['id'] as String,
      name: json['name'] as String,
      port: json['port'] as int,
      ip: json['ip'] as String? ?? 'localhost',
      icon: _getIconFromString(json['icon'] as String? ?? 'code'),
      isEnabled: json['isEnabled'] as bool? ?? false,
      isLocal: json['isLocal'] as bool? ?? false,
      isRunning: json['isRunning'] as bool? ?? false,
      tunnelId: json['tunnelId'] as String?,
      customDomain: json['customDomain'] as String?,
      protocol: json['protocol'] as String? ?? 'http', // 默认HTTP协议
      status: json['status'] as String?,
    );
  }
  
  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'port': port,
      'ip': ip,
      'icon': _getIconString(icon),
      'isEnabled': isEnabled,
      'isLocal': isLocal,
      'isRunning': isRunning,
      'tunnelId': tunnelId,
      'customDomain': customDomain,
      'protocol': protocol,
      'status': status,
    };
  }
  
  // 根据字符串获取图标
  static IconData _getIconFromString(String iconName) {
    switch (iconName) {
      case 'coffee':
        return Icons.coffee;
      case 'javascript':
        return Icons.javascript;
      case 'code':
        return Icons.code;
      case 'web':
        return Icons.web;
      case 'storage':
        return Icons.storage;
      case 'api':
        return Icons.api;
      default:
        return Icons.code;
    }
  }
  
  // 获取图标对应的字符串
  static String _getIconString(IconData icon) {
    if (icon == Icons.coffee) return 'coffee';
    if (icon == Icons.javascript) return 'javascript';
    if (icon == Icons.web) return 'web';
    if (icon == Icons.storage) return 'storage';
    if (icon == Icons.api) return 'api';
    return 'code';
  }
}